import jwt from 'jsonwebtoken'
import { db } from '../db'
import { refreshTokensTable } from '../db/schema/token'
import { eq, and, gt } from 'drizzle-orm'

export class TokenService {
  // 生成 Access Token (短期)
  static generateAccessToken(payload: { id: number; phone: string; role: string }) {
    if (!process.env.JWT_ACCESS_SECRET) {
      throw new Error('JWT_ACCESS_SECRET is not defined')
    }

    return jwt.sign(payload, process.env.JWT_ACCESS_SECRET, {
      expiresIn: '15m' // 15分钟
    })
  }

  // 生成 Refresh Token (长期)
  static generateRefreshToken(payload: { id: number }) {
    if (!process.env.JWT_REFRESH_SECRET) {
      throw new Error('JWT_REFRESH_SECRET is not defined')
    }

    return jwt.sign(payload, process.env.JWT_REFRESH_SECRET, {
      expiresIn: '7d' // 7天
    })
  }

  // 验证 Access Token
  static verifyAccessToken(token: string) {
    return jwt.verify(token, process.env.JWT_ACCESS_SECRET!) as any
  }

  // 验证 Refresh Token
  static verifyRefreshToken(token: string) {
    return jwt.verify(token, process.env.JWT_REFRESH_SECRET!) as any
  }

  // 保存 Refresh Token 到数据库
  static async saveRefreshToken(userId: number, token: string) {
    const expiresAt = new Date()
    expiresAt.setDate(expiresAt.getDate() + 7) // 7天后过期

    await db.insert(refreshTokensTable).values({
      userId,
      token,
      expiresAt
    })
  }

  // 验证并获取 Refresh Token
  static async validateRefreshToken(token: string) {
    const [refreshToken] = await db
      .select()
      .from(refreshTokensTable)
      .where(
        and(
          eq(refreshTokensTable.token, token),
          eq(refreshTokensTable.isRevoked, false),
          gt(refreshTokensTable.expiresAt, new Date())
        )
      )
      .limit(1)

    return refreshToken
  }

  // 撤销 Refresh Token
  static async revokeRefreshToken(token: string) {
    await db
      .update(refreshTokensTable)
      .set({ isRevoked: true })
      .where(eq(refreshTokensTable.token, token))
  }

  // 撤销用户的所有 Refresh Tokens
  static async revokeAllUserTokens(userId: number) {
    await db
      .update(refreshTokensTable)
      .set({ isRevoked: true })
      .where(eq(refreshTokensTable.userId, userId))
  }
}
